package com.hmall.search.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.api.client.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.common.utils.CollUtils;
import com.hmall.search.domain.po.ItemDoc;
import com.hmall.search.domain.query.ItemPageQuery;
import com.hmall.search.domain.vo.PageVO;
import com.hmall.search.service.ISearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class SearchServiceImpl implements ISearchService {

    private final ItemClient itemClient;
    private RestHighLevelClient client;

    private final String INDEX_NAME = "items";

    {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://175.13.32.160:9200")
        ));
    }

    @Override
    public void saveItemById(Long itemId) {
        // 根据id查询商品
        List<ItemDTO> itemDTOS = itemClient.queryItemByIds(ListUtil.of(itemId));

        if (CollUtils.isEmpty(itemDTOS)) {
            return;
        }

        try {
            // 1.准备Request对象
            IndexRequest request = new IndexRequest(INDEX_NAME).id(itemId.toString());
            // 2.准备请求参数
            request.source(JSONUtil.toJsonStr(BeanUtil.copyProperties(itemDTOS.get(0), ItemDoc.class)), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("更新商品失败，商品id：" + itemId, e);
        }
    }

    @Override
    public void deleteItemById(Long itemId) {
        try {
            // 1.准备Request对象
            DeleteRequest request = new DeleteRequest(INDEX_NAME, itemId.toString());
            // 3.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("删除商品失败，商品id：" + itemId, e);
        }
    }

    // 手搓搜索
    @Override
    public PageVO<ItemDoc> search(ItemPageQuery query) {
        // 前端传递数据
        String key = query.getKey();
        log.info("数据为:{}", query);

        // 1.创建Request
        SearchRequest request = new SearchRequest("items");

        // 2.组织请求参数--判断前端是否传递数据
        // 全文检索
       /* if (key == null || "".equals(key)) {
            request.source().query(QueryBuilders.matchAllQuery());
        } else {
            request.source().query(QueryBuilders.matchQuery("name", key));
        }*/

        // 多条件查询
        buildBasicQuery(query, request, key);


        // 分页
        Integer pageNo = query.getPageNo();      // 页码
        Integer pageSize = query.getPageSize();  // 每业大小

        // 排序
        request.source().sort(
                query.getSortBy().isEmpty() ? "sold" : query.getSortBy(),
                SortOrder.valueOf(query.getIsAsc() ? "ASC" : "DESC")
        );


        // 分页参数
        request.source().from((pageNo - 1) * pageSize).size(pageSize);
        SearchResponse response = null;

        try {
            // 3.发送请求
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("SearchServiceImpl 类 PageVO 方法，发送请求出现异常:{}", e.getMessage());
            throw new RuntimeException(e);
        }


        // 4.解析响应
        return handleResponse(response, pageNo);
    }


    // Post
    @Override
    public Map<String, List<String>> searchPost(ItemPageQuery query) {

        Map<String, List<String>> data = new HashMap<>();
        data.put("category", List.of("手机", "曲面电视", "拉杆箱", "休闲鞋", "休闲鞋", "硬盘", "真皮包"));
        data.put("brand", List.of("希捷", "小米", "华为", "oppo", "新秀丽", "Apple", "锤子"));

        return data;


    }

    // 多条件查询
    private static void buildBasicQuery(ItemPageQuery query, SearchRequest request, String key) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        request.source().query(boolQueryBuilder);

        // match_all -- 关键字搜索
        if (key == null || "".equals(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", key));
        }
        // 条件过滤
        // 分类
        if (query.getCategory() != null && !query.getCategory().equals("")) {

            boolQueryBuilder.filter(QueryBuilders.termQuery("category", query.getCategory()));
        }

        // 品牌
        if (query.getBrand() != null && !query.getBrand().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", query.getBrand()));
        }


        // 价格
        if (query.getMinPrice() != null && query.getMaxPrice() != null) {
            boolQueryBuilder.filter(
                    QueryBuilders.rangeQuery("price")
                            .gte(query.getMinPrice())
                            .lte(query.getMaxPrice())
            );
        }
    }

    // 解析响应 em
    private PageVO<ItemDoc> handleResponse(SearchResponse response, Integer pageNo) {
        SearchHits searchHits = response.getHits();
        // 1.获取总条数
        Long total = searchHits.getTotalHits().value;

        // 2.遍历结果数组
        SearchHit[] hits = searchHits.getHits();

        List<ItemDoc> list = new ArrayList<>();

        for (SearchHit hit : hits) {
            // 3.得到_source，也就是原始json文档
            String source = hit.getSourceAsString();
            // 4.反序列化并打印
            ItemDoc item = JSONUtil.toBean(source, ItemDoc.class);
            list.add(item);
        }

        // 封装返回
        return PageVO.of(total, Long.getLong(pageNo.toString()), list);


    }
}
